package com.java.cg.user.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.fastjson.JSON;
import com.java.common.utils.JwtUtil;
import com.java.common.utils.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.java.cg.user.entity.User;
import com.java.cg.user.service.UserService;
import com.java.common.utils.PageUtils;
import com.java.common.utils.R;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;


/**
 * 用户表
 *
 * @author jiangli
 * @since 2020-02-15 21:54:30
 */
@RestController
@RequestMapping("user/user")
public class UserController {
	@Autowired
	private UserService userService;

	/**
	 * 添加积分
	 */
	@GetMapping("/points/add")
	public R addPoints(@RequestParam("points") Integer points) {
		// 获取用户名
		String username = TokenDecode.getUserInfo().get("username");
		userService.addPoints(username, points);
		return R.ok();
	}

	@GetMapping("/login")
	public R login(String username, String password, HttpServletResponse response) {
		// 判断账号是否正确
		User user = userService.getById(username);
		// 密码加密 BCrypt
		if (user != null && BCrypt.checkpw(password, user.getPassword())) {
			// 用户校验通过，生成令牌，保存到客户端(cookie)
			// arg01:id唯一的ID  arg02: 载荷信息  arg03：token过期时间不设置默认一个小时
			Map<String, Object> map = new HashMap<>();
			map.put("role", "ROLE_USER");
			map.put("status", "SUCCESS");
			map.put("userinfo", user);
			// 将map转String
			String info = JSON.toJSONString(map);
			String token = JwtUtil.createJWT(IdUtil.randomUUID(), info, null);
			// 将token存到客户端(cookie)
			Cookie cookie = new Cookie("Authorization", token);
			cookie.setDomain("localhost"); //域名
			cookie.setPath("/"); //设置到跟路径下
			response.addCookie(cookie);
			return R.ok();
		}
		return R.error("账号或密码错误！！");
	}

	/**
	 * 列表
	 * 只允许拥有admin角色的用户访问
	 */
	@RequestMapping("/list")
	@PreAuthorize("hasRole('ADMIN')")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = userService.queryPage(params);

		return R.ok().put("page", page);
	}


	/**
	 * 信息
	 */
	@GetMapping({"/info/{username}", "/load/{username}"})
	public User info(@PathVariable("username") String username) {
		return userService.getById(username);
	}

	/**
	 * 保存
	 */
	@RequestMapping("/save")
	public R save(@RequestBody User user) {
		userService.save(user);

		return R.ok();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	public R update(@RequestBody User user) {
		userService.updateById(user);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	public R delete(@RequestBody String[] usernames) {
		userService.removeByIds(Arrays.asList(usernames));

		return R.ok();
	}

	public static void main(String[] args) {
		String hashed = BCrypt.hashpw("123456", BCrypt.gensalt());
		boolean checkpw = BCrypt.checkpw("123456", hashed);
		System.out.println(hashed);
		System.out.println(checkpw);
	}
}
